//
//  LiTableView.m
//  
//
//  Created by 李晓东 on 17/11/23.
//
//

#import "LiTableView.h"



#define RefreshViewHeight 60


@interface LiTableView ()
@property (nonatomic, strong) ResultOfDoubleChromosphere resultBlock;
@property (nonatomic, strong) TableContentOffsetBlock contentOffsetBlock;


@property (strong, nonatomic) UIView *refreshView;
@property (nonatomic, strong) UIImageView *refreshImageView;

@property (nonatomic, strong) UITextField *refreshTipField;

@property (nonatomic, strong) PullUpDoubleChromsphereBlock pullUpBlock;

@property (nonatomic, strong) NSTimer *timer;

@end

@implementation LiTableView

- (instancetype)initWithFrame:(CGRect)frame{
    if (self = [super initWithFrame:frame]) {
        [self initFrame];
        [self addObserver:self forKeyPath:@"contentOffset" options:NSKeyValueObservingOptionNew | NSKeyValueObservingOptionOld context:nil];
        
    }
    return self;
}

- (instancetype)initWithBlock:(ResultOfDoubleChromosphere)block andPullUpBlock:(PullUpDoubleChromsphereBlock)pullUpBlock{
    if (self = [super init]) {
        self.resultBlock = block;
        self.pullUpBlock = pullUpBlock;
    }
    return self;
}


// 初始化 View 的 frame
- (void)initFrame{
    self.refreshView = [[UIView alloc]init];
    self.refreshImageView = [[UIImageView alloc]init];
    
    [self addSubview:self.refreshView];
    [self.refreshView addSubview:self.refreshImageView];
    
    
    [self.refreshView setFrame:CGRectMake(0, 0, self.frame.size.width, 0)];
    CGFloat centerX = (self.frame.size.width - RefreshViewHeight) / 2;
    [self.refreshImageView setFrame:CGRectMake(centerX, 0, 0, 0)];
    
    // tempCode
    CGFloat tipCenterX = (self.frame.size.width - RefreshViewHeight*2) / 2;
    self.refreshTipField = [[UITextField alloc]initWithFrame:CGRectMake(tipCenterX, 20, RefreshViewHeight*2, 44)];
    [self.refreshTipField setText:@"fuck me"];
    [self.refreshTipField setBackgroundColor:[UIColor yellowColor]];
    [self addSubview:self.refreshTipField];
}

- (void)addObserverForContentOffset:(TableContentOffsetBlock)block{
    
}

- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSKeyValueChangeKey,id> *)change context:(void *)context{
    
    if ([keyPath isEqualToString:@"contentOffset"]) {
        CGPoint point = [change[NSKeyValueChangeOldKey] CGPointValue];
        NSLog(@"NSKeyValueChangeOldKey-%f", point.y);
        BOOL isDragging = self.isDragging;
        if (isDragging && point.y > RefreshViewHeight * -1 && point.y <= 0) {
            self.state = pulling;
            
            CGRect refreshFrame = self.refreshView.frame;
            CGRect refreshImageFrame = self.refreshImageView.frame;
            refreshFrame.size.height = fabs(point.y);
            refreshFrame.origin.y = point.y;
            self.refreshView.frame = refreshFrame;
            refreshImageFrame.size.width = fabs(point.y);
            refreshImageFrame.size.height = fabs(point.y);
            CGFloat centerX = (self.frame.size.width - refreshImageFrame.size.width) / 2;
            refreshImageFrame.origin.x = centerX;
            self.refreshImageView.frame = refreshImageFrame;
            
            [self setImageInView:fabs(point.y)];
        }
        
        if (!isDragging && point.y <= RefreshViewHeight * -1) {
            if (self.state == refreshing) {
                return;
            }
            
            self.state = refreshing;
            
        }
        
        if (!isDragging && point.y + self.frame.size.height > self.contentSize.height + 40 && point.y > 0) {
            if (self.state == loading) {
                return;
            }
            self.state = loading;
            NSLog(@"well done");
            
        }
        
    }
}



- (void)setImageInView:(CGFloat)offsetHeight{
    // 1/60 = 20/100*x;x=0.08333333.... when the num of pic had changed, you should use program like this i * 1 / 60 = 20 / 60 * x * i
    NSInteger picNum = MIN(MAX(offsetHeight, 1), 60);
    ;
    UIImage *image = [UIImage imageNamed:[NSString stringWithFormat:(picNum < 10 ? @"dropdown_anim__%04ld.png" : @"dropdown_anim__%05ld.png"), picNum]];
    CGFloat scale = picNum * 0.0167;
    image =[[UIImage alloc]initWithCGImage:image.CGImage scale:scale orientation:UIImageOrientationUp];
    self.refreshImageView.image = image;
    
}

// 访问网络,获取数据
- (void)loadData{
    [[[ThroadToServer shareThroadToServer]initWithParams:^(NSArray *array2){
        DoubleChromosphere *lastestObj = (DoubleChromosphere *)array2.lastObject;
        NSArray *array = [NSArray arrayWithObject:lastestObj];
        self.resultBlock(array);
        
        [self refreshingView];
    }] loadDoubleChromosphereByIssueno:nil];
    
}

- (void)finishLoading{
    [_timer invalidate];
    [self refreshingView];
}

- (void)refreshingView{
    UIEdgeInsets tableInset = self.contentInset;
    tableInset.top = 0;
    
    // tempCode
    CGRect tempFrame = self.refreshTipField.frame;
    tempFrame.origin.y = 50;
    dispatch_async(dispatch_get_main_queue(), ^{
        [UIView animateWithDuration:0.6 animations:^{
            self.contentInset = tableInset;
            
        } completion:^(BOOL finished) {
            
            self.refreshTipField.frame = tempFrame;
            [self.refreshImageView stopAnimating];
        }];
    });
    
}

- (void)refreshingOperate{
    
    UIEdgeInsets tableInset = self.contentInset;
    CGPoint tableOffset = self.contentOffset;
    tableInset.top = RefreshViewHeight;
    
    self.contentInset = tableInset;
    self.contentOffset = tableOffset;
    
    self.refreshImageView.animationImages = @[[UIImage imageNamed:@"eat-1.png"], [UIImage imageNamed:@"eat-2.png"], [UIImage imageNamed:@"eat-3.png"]];
    self.refreshImageView.animationDuration = 0.4;
    self.refreshImageView.startAnimating;
    
    [self emulate];
}

- (void)setState:(RefreshingState)state{
    _state = state;
    switch (state) {
        case idle:
            
            break;
        case pulling:
            
            break;
        case refreshing:
            [self refreshingOperate];
            break;
        case loading:
            self.pullUpBlock(nil);
            break;
        default:
            break;
    }
}

- (void)emulate{
    _timer = [NSTimer timerWithTimeInterval:3.0 target:self selector:@selector(loadData) userInfo:nil repeats:NO];
    [[NSRunLoop mainRunLoop]addTimer:_timer forMode:NSRunLoopCommonModes];
    
}

- (void)dealloc{
    [self removeObserver:self forKeyPath:@"contentOffset"];
}

@end
